#!/bin/sh

# define echo terminal style
# color: 0~6 --> black, red, green, yellow, blue, purple, cyan, grey
export ECHO_STYLE_00="\033[0m"        # default style(black background, white foreground)
export ECHO_STYLE_01="\033[41;33;1m"  # red background, yellow foregound bold
export ECHO_STYLE_02="\033[42;34;1m"  # red background, yellow foregound bold

#fix build kerenl when set chinese  as system language.
export LANG="en_US.UTF-8"
export LANGUAGE="en"
export TOPDIR=`pwd`
export echo="echo"

#echo -e "${ECHO_STYLE_01}echo command terminal style example${ECHO_STYLE_00}"

ok_count=0
fail_count=0


load_compile_count()
{
        if [ -e .compile_count ] ; then
                ok_count=$(cat .compile_count | grep ok | awk -F '=' {'print $2'})
                fail_count=$(cat .compile_count | grep fail | awk -F '=' {'print $2'})
        fi
}

check_bash()
{
        is_bash=$(ls -l /bin/sh | grep bash)
        if [ "$is_bash" = "" ] ; then
                hyphen_e=""
        else
                hyphen_e="-e"
        fi
}


docker_image_name=openwrt_cc_
docker_image_ver=v1
FTPADDR=ftp://soft:83583000@192.168.1.154:14147/openwrt_cat6
container_prefix=openwrt_cat6
dockerimagever=
CURDIRNAME=`pwd |tr // _ `
coolparam=$*

addtodockergroup()
{
	inGroup=$(id | grep docker)
	if [ "$inGroup" = "" ] ; then
		sudo usermod -a -G docker `whoami`
	fi
}

docker_run()
{
	addtodockergroup
       container=$(docker ps -a | grep $container_prefix$dockerimagever$CURDIRNAME)
       if [ "$container" = "" ] ; then
               echo "It seem you never build this system...."
               docker run -i -t  -v $TOPDIR:/$container_prefix -v /lib/modules:/lib/modules -v /usr/src:/usr/src  --name $container_prefix$dockerimagever$CURDIRNAME  -w /$container_prefix $docker_image_name$docker_image_ver ./cool $coolparam
       else
               docker start $container_prefix$dockerimagever$CURDIRNAME
               #docker exec -it $container_prefix$dockerimagever$CURDIRNAME bash
               docker exec -it $container_prefix$dockerimagever$CURDIRNAME ./cool $coolparam
		#docker exec -it $container_prefix$dockerimagever$CURDIRNAME bash
       fi
}


check_ubuntu_version()
{
	ubuntu_version=`cat /etc/issue | awk '{print $2}' | awk -F '.' '{print $1}'`
	if [ "${ubuntu_version}" != "14" -a "${ubuntu_version}" != "15" -a "${ubuntu_version}" != "16" ]; then
		get_docker=$(which docker)
		if [ "$get_docker" = "" ]; then
			wget ftp://192.168.1.123/sqn3220/docker/get-docker.sh -nv -m -nH --restrict-file-name=nocontrol --cut-dirs=2
			sudo sh get-docker.sh --mirror Aliyun
			sudo usermod -a -G docker `whoami`
		fi
		get_images=$(docker images | grep $docker_image_name$docker_image_ver)
		if [ "$get_images" = "" ]; then
			wget $FTPADDR/$docker_image_name$docker_image_ver.tar.gz
			sudo docker load -i $docker_image_name$docker_image_ver.tar.gz
		fi
		docker_run
		rm -f $docker_image_name$docker_image_ver.tar.gz
		rm -f get-docker.sh
		exit
	fi
}

check_is_docker()
{
	system_is_docker=$(ls -a / | grep dockerenv)
	if [ "$system_is_docker" = "" ] ; then
		check_ubuntu_version
	fi
}

LASTDOCS=.doc20190612
download_something()
{
	download_flag=.flag_${project}_download_something_2018_12_20
	if [ ! -f ${download_flag} ]; then
		touch ${download_flag}
		wget ${FTPADDR}/${project}/some-bin/factory.bin -O project/${project}/bin/factory.bin
		wget ${FTPADDR}/${project}/some-bin/old-all.bin -O project/${project}/bin/old-all.bin
			
	fi
        if [ ! -e $LASTDOCS ] ; then
                mkdir document -p
                cd document
                wget ${FTPADDR}/document -nv -m -nH --restrict-file-name=nocontrol --cut-dirs=2
                cd $TOPDIR
                touch $LASTDOCS
        fi

}

download_some_dl()
{
	if [ ! -f dl/linux-firmware-2015-03-20-f404336ba808cbd57547196e13367079a23b822c.tar.bz2 ]; then
		wget ftp://192.168.1.123/qsdk/dl/linux-firmware-2015-03-20-f404336ba808cbd57547196e13367079a23b822c.tar.bz2 -O dl/linux-firmware-2015-03-20-f404336ba808cbd57547196e13367079a23b822c.tar.bz2
	fi
}

check_is_docker

date_start=$(date +%s)
if [ "$1" = "" ] ; then
echo ****************************主菜单****************************
echo cpe
echo "默认mt7621 cat6模块"
echo "  1:   s21 (mt7621 cat6模块)"
echo "  2:   w13 (mt7628)"
echo other:
echo "  y:   看看每个人在当前分支上的提交次数吧"
echo "  z:   看看每个月的提交次数吧"
echo "  q:   quit"

read line
else
line=$1
fi

if [ "$line" = "" ]; then
	line="1"
fi



if [ "$line" = "1" -o "$line" = "s21" ] ; then
	project=s21
	chip="mt7621"
elif [ "$line" = "2" -o "$line" = "w13" ] ; then
	project=w13
	chip="mt7628"
elif [ "$line" = "y" ] ; then
        git log --pretty='%aN' | sort | uniq -c | sort -k1 -n -r
        echo ------------------------------------------------
        echo "  " ` git log --pretty='%aN' | wc -l `   all
        exit
elif [ "$line" = "z" ] ; then
        git log --date short --pretty=format:%ad |  cut -b -7  | sort -r | uniq -c
        echo ------------------------------------------------
        echo "  " ` git log --pretty='%aN' | wc -l `   all
        exit
elif [ "$line" = "q" ] ; then
        exit;
else
        exit
fi


download_something
download_some_dl
load_compile_count
check_bash
#check_ubuntu_version

export TZ_PROJECT=${project}
echo "The project is ${project}"


if [ "$2" = "" ]; then
	echo ****************************编译选项****************************
	echo "默认快速编译"
	echo "  1:   快速编译"
	echo "  2:   完全编译"
	echo "  a:   配置openwrt编译选项"
	echo "  b:   配置kernel"
	echo "任意包名,例如：package/ramips/applications/dialtool2"
	echo "  q:   quit"
	read options
	
	if [ "$options" = "" ]; then
		options=1
	fi
else
	options=$2
fi

echo "options is" $options

if [ ! -d "${TOPDIR}/project/${project}/rootfs" ]; then
	mkdir ${TOPDIR}/project/${project}/rootfs
fi

if [ -f ${TOPDIR}/project/${project}/key-message ]; then
	TZ_BRANCH_NAME=`git branch -a| grep \* | cut -f2 -d" "`
	TZ_RELEASE_NAME=`lsb_release -i|cut -f2`
	GIT_COMMIT_SHA1=`git rev-parse --verify HEAD`
	BUILD_TIME=`date +%F_%H:%M`
	cp ${TOPDIR}/project/${project}/key-message ${TOPDIR}/project/${project}/rootfs/version
	if [ ${project} = "w13" ]; then
		echo "type=P11IDU" >> ${TOPDIR}/project/${project}/rootfs/version
	else
		echo "projectType=${project}" >> ${TOPDIR}/project/${project}/rootfs/version
	fi
	echo "branch=${TZ_BRANCH_NAME}" >> ${TOPDIR}/project/${project}/rootfs/version
	echo "os=${TZ_RELEASE_NAME}" >> ${TOPDIR}/project/${project}/rootfs/version
	echo "sha1=${GIT_COMMIT_SHA1}" >> ${TOPDIR}/project/${project}/rootfs/version
	echo "build=${BUILD_TIME}" >> ${TOPDIR}/project/${project}/rootfs/version
fi

compile_result="fail"

if [ "$options" = "1" ]; then
	echo "快速编译"
	cp config/default_openwrt_${project}_config .config
	cp config/default_kernel_${project}_config target/linux/ramips/${chip}/config-3.18
	make V=99 -j 8
elif [ "$options" = "2" ]; then
	echo "完全编译(暂时不支持)"
elif [ "$options" = "a" ]; then
        echo "配置openwrt编译选项"
	cp config/default_openwrt_${project}_config .config
	make menuconfig
	cp .config config/default_openwrt_${project}_config
	exit
elif [ "$options" = "b" ]; then
        echo "配置kernel"
	cp config/default_kernel_${project}_config target/linux/ramips/${chip}/config-3.18
	make kernel_menuconfig
	cp target/linux/ramips/${chip}/config-3.18 config/default_kernel_${project}_config
	exit
elif [ "$options" = "q" ]; then
	exit
else
	echo "make $options/{clean,prepare,compile} V=99"
	make $options/clean V=99
	make $options/prepare V=99
	make $options/compile V=99
fi

if [ "$?" = "0" ] ; then
        compile_result="ok"
        ok_count=$(($ok_count+1))
else
        fail_count=$(($fail_count+1))
fi

echo "compile_result is" $compile_result

if [ $compile_result = "ok" ]; then
	if [ "$options" = "1" ] || [ "$options" = "2" ] ; then
#		mkdir -p image/7621_cat6
#		cp -f bin/ramips/openwrt-ramips-mt7621-sxx-u-boot.bin image/7621_cat6/ 
#		cp -f bin/ramips/openwrt-ramips-mt7621-zbt-wg2626-squashfs-sysupgrade.bin image/7621_cat6/
#		rm image/7621_cat6/firmware.bin -rf
#		tr '\000' '\377' < /dev/zero | dd of=image/7621_cat6/firmware.bin bs=1024 count=16384 2>/dev/null
#		dd if=image/7621_cat6/openwrt-ramips-mt7621-sxx-u-boot.bin of=image/7621_cat6/firmware.bin conv=notrunc 2>/dev/null
#		dd if=image/7621_cat6/openwrt-ramips-mt7621-zbt-wg2626-squashfs-sysupgrade.bin of=image/7621_cat6/firmware.bin conv=notrunc bs=64k seek=5 2>/dev/null
#		cp image/7621_cat6/begin.bin image/7621_cat6/olduboot_newfirmware.bin -f
#		tr '\000' '\377' < /dev/zero | dd of=image/7621_cat6/emptyfirmware.bin bs=1024 count=6144 2>/dev/null
#		dd if=image/7621_cat6/emptyfirmware.bin of=image/7621_cat6/olduboot_newfirmware.bin conv=notrunc bs=64k seek=5 2>/dev/null
#		dd if=image/7621_cat6/openwrt-ramips-mt7621-zbt-wg2626-squashfs-sysupgrade.bin of=image/7621_cat6/olduboot_newfirmware.bin conv=notrunc bs=64k seek=5 2>/dev/null
		. project/${project}/formImage.sh
	fi
fi

cd ${TOPDIR}
echo "ok_count=$ok_count" > .compile_count
echo "fail_count=$fail_count" >> .compile_count

date_end=$(date +%s)
echo `date`

echo  $hyphen_e "${ECHO_STYLE_01}\n本次操作运行了：$((date_end-date_start))秒\n${ECHO_STYLE_00}"
echo compile counts ok:$ok_count fail:$fail_count

if [ "$compile_result" = "fail" ] ; then
        echo  $hyphen_e "\033[;31m 路漫漫其修远兮.... \033[0m"
        exit 1
else
	echo  $hyphen_e "\033[;32m 会当凌绝顶 一览众山小\033[0m"
fi

